package com.sakura.二分查找;

public class Code34_在排序数组中查找元素的第一个和最后一个位置 {

    public int[] searchRange(int[] nums, int target) {
        int start = lowerBound(nums, target);
        if (start == nums.length || nums[start] != target) {
            return new int[]{-1, -1}; // nums 中没有 target
        }
        int end = lowerBound(nums, target + 1) - 1;
        return new int[]{start, end};
    }

    public int lowerBound(int[] nums, int target) {
        int left = -1;
        int right = nums.length;

        while (left + 1 < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] >= target) {
                right = mid;
            } else {
                left = mid;
            }
        }
        return right;
    }
}
